﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using PrearrangedChaos.AgileZen.Service.Model;
using PrearrangedChaos.AgileZen.Service.Rest;

namespace PrearrangedChaos.AgileZen.Service
{
    internal class ZenResourceCollectionEnumerator<TCollection, TModel> : IEnumerator<TModel>
        where TModel : IModel
        where TCollection : class, IPagingResponse<TModel>
    {
        private readonly RestArguments _ids;
        private ZenClient _client;
        private IEnumerator<TModel> _enumerator;

        public ZenResourceCollectionEnumerator(string apiKey, RestArguments ids)
        {
            this._ids = ids;
            this._client = new ZenClient(apiKey);
            this.Reset();
        }

        ~ZenResourceCollectionEnumerator()
        {
            this.Dispose();
        }

        public void Dispose()
        {
            if (this._client == null)
                return;
            
            this._client.Dispose();
        }

        public bool MoveNext()
        {
            return this._enumerator.MoveNext();
        }

        public void Reset()
        {
            this._enumerator = this._client.GetCollection<TCollection, TModel>(this._ids).
                SelectMany(pages => pages.GetItems()).GetEnumerator();
        }

        public TModel Current
        {
            get { return this._enumerator.Current; }
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }
    }
}
